from pyhive import hive
from DBUtils.PooledDB import PooledDB
from pymysql import *
conn = Connection(host='localhost',user='root',password='qinxiao123456',database='bigdata',port=3306)

# 创建 Hive 连接池
# hive_pool = PooledDB(
#     creator=hive.Connection,  # 使用 pyhive 的 hive.Connection 作为连接创建器
#     host='master',
#     port=10000,
#     username='qx',
#     maxconnections=10,  # 最大连接数
# )


def execute_query_schema(query, params=None):
    """执行查询并返回结果"""
    # conn = hive_pool.connection()
    cursor = conn.cursor()
    try:
        cursor.execute(query, params)
        columns = [col[0] for col in cursor.description]
        results = cursor.fetchall()
        return columns, results
    finally:
        # cursor.close()
        # conn.close()
        pass

def execute_query(query, params=None):
    """执行查询并返回结果"""
    # conn = hive_pool.connection()
    cursor = conn.cursor()
    try:
        cursor.execute(query, params)
        if query.strip().lower().startswith('select'):
            columns = [col[0].split("\.")[-1] for col in cursor.description]
            results = cursor.fetchall()
            return columns, results
        else:
            conn.commit()
            return cursor.fetchall()
    finally:
        # cursor.close()
        # conn.close()
        pass